package com.wwc.common.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wwc.common.context.LoginMemberContext;
import com.wwc.common.response.MemberLoginResponse;
import com.wwc.common.utils.JwtUtil;
import jakarta.annotation.Nonnull;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 拦截器：Spring框架特有的，常用于登录校验，权限校验，请求日志打印
 */
@Component
public class MemberInterceptor implements HandlerInterceptor{
	private static final Logger LOG = LoggerFactory.getLogger(MemberInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull Object handler){
		// 获取header的token参数
		String token = request.getHeader("token");
		if(StrUtil.isNotBlank(token)){
			LOG.info("获取会员登录token：{}", token);
			JSONObject loginMember = JwtUtil.getJSONObject(token);
			LOG.info("当前登录会员：{}", loginMember);
			MemberLoginResponse member = JSONUtil.toBean(loginMember, MemberLoginResponse.class);
			LoginMemberContext.setMember(member);
		}
		return true;
	}
}
